package it.tcm.TeacherClassMate.servlet;

import it.tcm.TeacherClassMate.beans.OrderMainBean;
import it.tcm.TeacherClassMate.facade.OrderMainManageBase;
import it.tcm.TeacherClassMate.persistent.DBConnection;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;

import org.apache.log4j.Logger;


public class DownloadResult extends HttpServlet{
	
	
	 /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(this.getClass());

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException {
		  Blob docx = null;
		  Connection conn = null;
		  Statement stmt = null;
		  ResultSet rs = null;
		  ServletOutputStream out = null;
		
		  try{
				
			  String id = request.getParameter("id");
			  OrderMainManageBase ommb = new OrderMainManageBase();
			  OrderMainBean omb = ommb.getOrderMainById(Integer.valueOf(id));
			  Long time = new Long(new Date().getTime());
			  String filename = omb.getUserId() + "-" + time.toString() + "_result.docx";
			  out = response.getOutputStream();
			  DBConnection db = new DBConnection();
			  conn = db.getDBConnection();
			  stmt = conn.createStatement();
			  rs = stmt.executeQuery("select RESULT from ORDERMAIN where id = " + id);
			  InputStream in = null;
			  if (rs.next()) {
				  docx = rs.getBlob(1);
				  response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");			
				  response.setHeader("Content-Disposition", "attachment; filename=" + filename);
				  in = docx.getBinaryStream();
				  int length = (int) docx.length();
				  int bufferSize = 1024;
				  byte[] buffer = new byte[bufferSize];
				  while ((length = in.read(buffer)) != -1) {
					  out.write(buffer, 0, length);
				  }
			  }
			  in.close();
			  out.flush();
		  } catch (Throwable e) {
				 System.out.println("catch exception " +  e.getMessage()); 
				  e.printStackTrace();
				  return;
		  } finally {
				  try {
				  rs.close();
				  stmt.close();
				  conn.close();
				  } catch (SQLException e) {
				  e.printStackTrace();
			  }
		  }
			 
	}


	  protected void doPost(HttpServletRequest request, HttpServletResponse response)
	      throws ServletException, IOException 
	  {
		  
	  }      
	  
	  public String getServletInfo()
	  {
	    return super.getServletInfo();
	  }
	
	
	

}

